<template>
    <bi-form ref="form" >
        <bi-form-item label="模型名称">
            <bi-input v-model="form.name"></bi-input>
        </bi-form-item>
        <bi-form-item label="关联表">
            <bi-input v-model="form.table"></bi-input>
        </bi-form-item>

        <bi-form-item label="表主键">
            <bi-select v-model="form.key" :option="fieldList"></bi-select>
        </bi-form-item>

        <bi-form-item label="模型描述">
            <bi-textarea v-model="form.comment"></bi-textarea>
        </bi-form-item>
    </bi-form>
</template>


<script>
export default{
    dialog:{
        loading:true
    },
    data(){
        let form = {
            name:'',
            table: '',
            key:'',
            comment:''
        }
        
        form = this.$assign(form,this.item);


        function capitalizeAfterUnderscore(app,str) {
              
            if (str.indexOf(app+'_')===0){
                //删除前面的字符串
                str = str.substr((app+'_').length);
                
            }
            str = str.charAt(0).toUpperCase() + str.slice(1);
            return str.replace(/_([a-z])/g, function (_, char) {
                return char.toUpperCase();
            });
        }


        if (form.name == ''){
            form.name = capitalizeAfterUnderscore(this.app,form.table);
        }

        return {
            form,
            fieldList:[],
        }
    },
    props:{
        app:String,
        config:String,
        item:{
            type:Object,
            default:{}
        },
    },
    methods:{
        dialogOk(){
            if (this.$refs.form.check()){
                this.$ajax({
                    url:this.$url({controller:'database',action:'modelEdit'}),
                    data:{
                        app:this.app,
                        config:this.config,
                        ...this.form
                    },
                    success:(res)=>{
                        this.$message.success('操作成功');
                        this.$emit('ok');
                    }
                });
            }
        }
    },
    mounted(){
        this.$ajax({
            url:this.$url({controller:'database',action:'tableField'}),
            data:{
                app:this.app,
                config:this.config,
                table:this.form.table,
            },
            success:(res)=>{
                if(this.form.key ==''){
                    this.form.key = res[0];
                }else{
                    if (res.indexOf(this.form.key) == -1){
                        //将值插入到第一个
                        res.unshift(this.form.key);
                    }
                }
                this.fieldList = res;
                this.dialog.loading = false;
            }
        });
    },
}
</script>